﻿using Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service
{
    public class ArticleService : IDisposable
    {
        Model1 db = new Model1();

        //查询指定栏目的前几条文章
        public List<V_CMS_Article> SelectTops(int cid, int top)
        {
            return db.V_CMS_Article
                .Where(x => x.state == 2 && x.cid == cid)
                .OrderByDescending(x => x.istop)
                .OrderByDescending(x => x.aid)
                .Take(top).ToList();
        }

        //分页查询用户列表
        public PagingList<CMS_User> Paging(int page, int rows, string uname, bool? admin)
        {
            //准备Linq语句
            var linq = db.CMS_User.Where(x => true);
            //姓名查询
            if (!string.IsNullOrEmpty(uname))
                linq = linq.Where(x => x.uname.Contains(uname));
            //是否为管理员
            if (admin == true && admin != false)
                linq = linq.Where(x => x.admin == true);
            else if (admin != true && admin == false)
                linq = linq.Where(x => x.admin == false);
            //查询总记录数
            var plist = new PagingList<CMS_User>();
            plist.total = linq.Count();
            //查询分页数据
            plist.rows = linq
                .OrderByDescending(x => x.admin)
                .OrderByDescending(x => x.uid)
                .Skip((page - 1) * rows).Take(rows)
                .ToList();
            return plist;
        }

        //添加用户
        public bool Add(CMS_User u)
        {
            //添加操作
            db.Entry(u).State = EntityState.Added;
            //提交事务
            db.SaveChanges();
            //添加成功
            return true;
        }


        //修改用户
        public bool Update(CMS_User u)
        {
            //进行修改操作
            db.Entry(u).State = EntityState.Modified;
            //提交事务
            db.SaveChanges();
            //操作成功
            return true;
        }

        //加载用户信息
        public CMS_User Find(int uid)
        {
            return db.CMS_User.Find(uid);
        }

        //删除
        public bool remove(int uid)
        {
            CMS_User u = new CMS_User();
            u.uid = uid;
            //进行删除操作
            db.Entry(u).State = EntityState.Deleted;
            //提交作业
            db.SaveChanges();
            //操作成功
            return true;
        }


        //销毁
        public void Dispose()
        {
            db.Dispose();
        }
    }
}
